package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import sun.security.provider.ConfigFile;
import util.IdWorker;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;

@Service
@Transactional
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 新增吐槽
     */
    public void saveSpit(Spit spit){  // 完善新增
        spit.set_id(String.valueOf(idWorker.nextId()));
        // 补充默认值
        spit.setThumbup(0);
        spit.setComment(0);
        spit.setShare(0);
        spit.setVisits(0);
        spit.setState("1");
        // 判断该吐槽是否有父节点，如果有修改回复数
        if(spit.getParentid()!=null&&!"".equals(spit.getParentid())){
            // 设置条件
            Query query = new Query();
            // 将字段parentid设置为父节点的id
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            // 修改回复数
            Update update = new Update();
            update.inc("Comment",1);
            mongoTemplate.updateFirst(query,update,"spit");
        }
        spitDao.save(spit);
    }

    /**
     * 查询所有
     */
    public List<Spit> findAll() {
        if(redisTemplate.opsForValue().get("SpitAll")!=null){
            System.out.println("redis中获取");
            return (List<Spit>) redisTemplate.opsForValue().get("SpitAll");
        }
        List<Spit> list = spitDao.findAll();
        redisTemplate.opsForValue().set("SpitAll",list,1, TimeUnit.HOURS);
        System.out.println("添加到redis");
        return list;
    }

    /**
     * 根据id查询
     */
    public Spit findById(String spitId) {
        Optional<Spit> spit = spitDao.findById(spitId);
        if(spit.isPresent()){
            return spit.get();
        }
        return null;
    }

    /**
     * 根据id删除
     */
    public void deleteById(String spitId) {
        spitDao.deleteById(spitId);
    }

    /**
     * 修改
     */
    public void update(Spit spit) {
        spitDao.save(spit);
    }

    /**
     * 吐槽点赞
     */
    public Result adThumbup(String spitId) {
        String userName="Tom";
        if(redisTemplate.opsForValue().get("Spit_"+spitId)!=null){
            return new Result(StatusCode.ERROR,"不能重复点赞",false);
        }
        Spit spit = spitDao.findById(spitId).get();
        spit.setThumbup(spit.getThumbup()==null?1:spit.getThumbup()+1);
        spitDao.save(spit);
        redisTemplate.opsForValue().set("Spit_"+spitId,userName);
        return new Result(StatusCode.OK,"点赞成功",true);
    }

    /**
     * 根据条件查询Spit列表
     */
    public List<Spit> searchSpitList(@RequestBody Spit spit){
        return spitDao.findAll(new Example<Spit>() {
            @Override
            public Spit getProbe() {
                List<Spit> spits = new ArrayList<>();
                if(spit.getContent()!=null&&!"".equals(spit.getContent())){

                }
                return null;
            }

            @Override
            public ExampleMatcher getMatcher() {
                return null;
            }
        });
    }

    /**
     *Spit分页
     */
    public Page<Spit> searchSpitByPage(Spit spit,Integer page,Integer size){
        Pageable pageable = PageRequest.of(page - 1, size);
        return null;
    }

    /**
     * 根据上级ID查询吐槽数据（分页）
     */
    public Page<Spit> searchSpitPage(String parentid,Integer page,Integer size){
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Spit> spitPage = spitDao.findByParentid(parentid, pageable);
        return spitPage;
    }
}
